package com.agrm.rabc.controller;

import com.agrm.model.common.dtos.ResponseResult;
import com.agrm.model.rabc.dto.Group;
import com.agrm.rabc.service.GroupService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping(value = "/api/v1/groups", produces = MediaType.APPLICATION_JSON_VALUE)
public class GroupApi {
    private GroupService groupService;

    @Autowired
    public void setGroupService(GroupService groupService) {
        this.groupService = groupService;
    }

    @GetMapping
    public ResponseResult findAll(Group group,
                                  @RequestParam(defaultValue = "1") Integer pageNo,
                                  @RequestParam(defaultValue = "10") Integer pageSize) {
        Page<Group> page = new Page<>(pageNo, pageSize);
        page = groupService.findAll(group, page);
        return ResponseResult.okResult(page);
    }

    @GetMapping("/id/{id}")
    public ResponseResult findById(@PathVariable("id") Integer id) {
        Group group = groupService.findById(id);
        if (group == null) {
            return ResponseResult.errorResult(-1,"未查询到指定编号的组");
        } else {
            return ResponseResult.okResult(group);
        }
    }

    @PostMapping
    public ResponseResult save(@RequestBody Group group) {
        boolean success = groupService.save(group);
        if (success) {
            return ResponseResult.okResult(200,"保存成功！");
        } else {
            return ResponseResult.errorResult(-1,"保存组失败");
        }
    }

    @PutMapping
    public ResponseResult update(@RequestBody Group group) {
        boolean success = groupService.update(group);
        if (success) {
            return ResponseResult.okResult(200,"更新成功");
        } else {
            return ResponseResult.errorResult(-1,"修改组失败");
        }
    }

    @DeleteMapping
    public ResponseResult deleteByIds(@RequestBody Integer[] ids) {
        int count = groupService.deleteByIds(List.of(ids));
        if (count > 0) {
            return ResponseResult.okResult(count);
        } else {
            return ResponseResult.errorResult(-1,"删除组失败");
        }
    }
}
